package com.zhongke.common.base.viewmodel

import androidx.lifecycle.*
import com.zhongke.core.http.httpbase.HttpResultState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import java.io.Serializable
import java.lang.Exception

/**
 *
 */
open class ZKBaseViewModel<M : ZKBaseModel?> @JvmOverloads constructor(protected var model: M? = null) :
    ViewModel(), ZKIBaseViewModel, Serializable {

    private var tokenAny: MutableLiveData<HttpResultState<Any>> = MutableLiveData()


    private var requestPublicKeyCount = 0


    override fun onCleared() {
        super.onCleared()
        if (model != null) {
            model!!.onCleared()
        }
    }

    /**
     * 统一处理token失效或者账号被挤掉的情况
     */
    fun dealTokenInvalid(code: Int,msg: String?){
//        if (code == ZKConstant.ACCOUNT_LOGOUT
//            || code == ZKConstant.ACCOUNT_INVALID
//            || code == ZKConstant.ACCOUNT_SQUEEZE_OUT) { //账号被挤，需要重新登录
//            logoutAccount()
//            startGuide()
//            if (code != ZKConstant.ACCOUNT_LOGOUT && !TextUtils.isEmpty(msg)){
//                ZKToastUtils.showShort(ZKBaseApplication.getContext(),msg)
//            }
//        } else if (code == ZKConstant.TOKEN_INVALID && !ZKBaseApplication.getInstance().isHasRequestToken){//token失效
//            ZKBaseApplication.getInstance().isHasRequestToken = true
//            expireToken()
//        } else if (code == ZKConstant.SIGN_FAIL){
//            val publicKey = ZKSpUtil.getInstance().getStringValue(ZKConstant.ZKSP.PUBLIC_KEY)
//            if (TextUtils.isEmpty(publicKey)){
//                getPublicKey()
//            }
//        }
    }

    /**
     * 延长token
     */
    private fun expireToken(){
//        request({
//            ZKHttpApi.INSTANCE.getApi(ZKCommonApi::class.java).expireToken()
//        }, tokenAny, false)
    }

    fun getPublicKey(){
//        request({
//            ZKHttpApi.INSTANCE.getApi(ZKCommonApi::class.java).getPublicKey()
//        }, {
//            parsePublicKey(it)
//        }, {
//            parsePublicKey(null)
//        })
        requestPublicKeyCount++
    }

    /**
     * 解析公钥
     */
//    private fun parsePublicKey(response: ZKResponse<ZKPublicKeyBean>?) {
//        if (response == null || !response.isSuccess()) {
//            if (requestPublicKeyCount < 5) { //公钥获取失败后，尝试再发起请求
//                getPublicKey()
//            }
//        } else {
//            var publicKey = response.data.key
//            publicKey = publicKey?.replace("-----BEGIN PUBLIC KEY-----", "")
//            publicKey = publicKey?.replace("-----END PUBLIC KEY-----", "")
//            ZKSpUtil.getInstance().setStringValue(ZKConstant.ZKSP.PUBLIC_KEY, publicKey)
//        }
//    }
}